﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;

namespace JX.Infrastructure.Common
{
	/// <summary>
	/// 数据字段验证帮助类
	/// </summary>
	public class ValidatetionHelper
	{
        /// <summary>
        /// 检查字段是否通过验证。
        /// 例：var result = ValidatetionHelper.IsValid(要验证类的实例);
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static ValidResult IsValid(object value)
        {
            ValidResult result = new ValidResult();
            try
            {
                var validationContext = new ValidationContext(value);
                var results = new List<ValidationResult>();
                var isValid = Validator.TryValidateObject(value, validationContext, results, true);

                if (!isValid)
                {
                    result.IsVaild = false;
                    result.ErrorMembers = new List<ErrorMember>();
                    foreach (var item in results)
                    {
                        result.ErrorMembers.Add(new ErrorMember()
                        {
                            ErrorMessage = item.ErrorMessage,
                            ErrorMemberName = item.MemberNames.FirstOrDefault()
                        });
                    }
                }
                else
                {
                    result.IsVaild = true;
                }
            }
            catch (Exception ex)
            {
                result.IsVaild = false;
                result.ErrorMembers = new List<ErrorMember>();
                result.ErrorMembers.Add(new ErrorMember()
                {
                    ErrorMessage = ex.Message,
                    ErrorMemberName = "Internal error"
                });
            }

            return result;
        }

    }

    /// <summary>
    /// 验证结果返回类
    /// </summary>
    public class ValidResult
    {
        /// <summary>
        /// 错误字段的消息提示列表
        /// </summary>
        public List<ErrorMember> ErrorMembers { get; set; }
        /// <summary>
        /// 是否验证成功
        /// </summary>
        public bool IsVaild { get; set; } = false;
    }

    /// <summary>
    /// 验证错误的提示消息类
    /// </summary>
    public class ErrorMember
    {
        /// <summary>
        /// 错误的提示消息
        /// </summary>
        public string ErrorMessage { get; set; } = string.Empty;
        /// <summary>
        /// 错误字段的名称
        /// </summary>
        public string ErrorMemberName { get; set; } = string.Empty;
    }
}
